const shsDB = require("./../db/index.js");
// 敏感词对象
let mgcWordObj = {
	value: [], // 初始化为空数组，避免未定义错误
	code: "sensitiveWords",
	time: new Date().getTime() - 1 // 初始化为过去时间，确保首次请求时更新敏感词
};

// 响应对象模板
const responseTemplate = {
	code: 200,
	message: "success",
	status: false,
	highlightedText: "",
	error: null // 添加错误字段
};

// 从数据库获取敏感词
async function fetchSensitiveWords() {
	try {
		let sql = `SELECT * FROM dict WHERE code='${mgcWordObj.code}'`;
		let data = await shsDB(sql);
		if (data && data.length > 0) {
			mgcWordObj.value = data[0].value ? data[0].value.split(',') : [];
			mgcWordObj.time = new Date().getTime() + 2 * 60 * 60 * 1000;
		} else {
			throw new Error("No sensitive words found in the database.");
		}
	} catch (error) {
		console.error("Error fetching sensitive words:", error);
		throw error; // 重新抛出错误，以便在路由处理中捕获
	}
}

// 检测文本中的敏感词
function detectSensitiveWords(contentText) {
	let obj = {
		...responseTemplate
	};
	try {
		mgcWordObj.value.forEach(word => {
			const regex = new RegExp(`(${word})`, 'gi');
			if (regex.test(contentText)) {
				obj.status = true;
				obj.highlightedText = contentText.replace(regex, '<span style="color: red;">$1</span>');
				throw new Error("Sensitive word found.");
			}
		});
	} catch (error) {

	}
	return obj;
}

async function comSensitiveWords(contentText) {
	try {
		if (mgcWordObj.time < new Date().getTime()) {
			await fetchSensitiveWords();
		}
		return detectSensitiveWords(contentText);
	} catch (error) {
		// 捕获并处理任何在获取敏感词或检测过程中发生的错误
		return {
			status: false,
			highlightedText: "",
			code: 500,
			message: "Internal Server Error",
			error: error.message
		}
	}
}

module.exports = {
	comSensitiveWords
}